
#include "core/pool.h"

#include <assert.h>

void ve_pool_init( VEPool *pool, void *data, int chunk_size, int chunk_count )
{
	char *ptr_begin;
	char *ptr_end;

	assert( chunk_size >= sizeof(void*) );

	pool->free_chunk = 0;
	pool->chunk_size = chunk_size;
	pool->chunk_count = chunk_count;

	ptr_begin = (char*)data;
	ptr_end = ptr_begin + chunk_size*chunk_count;

	while( ptr_end > ptr_begin )
	{
		ptr_end -= chunk_size;
		*((void**)ptr_end) = pool->free_chunk;
		pool->free_chunk = ptr_end;
	}
}

void * ve_pool_alloc( VEPool *pool )
{
	void *chunk = pool->free_chunk;
	if( !chunk ) return 0;

	pool->free_chunk = *((void**)pool->free_chunk);
	pool->chunk_count--;
	return chunk;
}

void ve_pool_free( VEPool *pool, void *data )
{
	*((void**)data) = pool->free_chunk;
	pool->free_chunk = data;
	pool->chunk_count++;
}
